<template>
  <el-main>
    <el-form :inline="true" :model="user" ref="user" :rules="rules">

      <el-form-item label="登录名称" prop="name">
        <el-input v-model="user.name" placeholder="请输入登录名称"></el-input>
      </el-form-item>

      <el-form-item label="登录密码" prop="password">
        <el-input v-model="user.password" type="password" placeholder="请输入登录密码"></el-input>
      </el-form-item>
      <el-row>
        <el-button @click="login" type="success">登录</el-button>
      </el-row>

    </el-form>
  </el-main>
</template>

<script>
export default {
  name: "list",
  data(){
    return {
      user:{
        name:'admin',
        password:'admin'
      },
      rules:{
        name:[
          { required: true, message: '请输入登录名', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods:{
    login(){
      let user = this.user;
      console.log(user);

      //发送ajax请求，后台验证用户，如果验证成功，给前台返回一个token（用户id或登录名称）
      this.axios.post("http://localhost:8200/user/login",user).then(res=>{
        if(res.data.result){
          console.log("res======>",res);
          //存储用户信息到localStorege
          let userInfo = res.data.data;
          let userInfoStr = JSON.stringify(userInfo);
          localStorage.setItem("token",userInfoStr);
          //保存用户信息到vuex：store
          this.$store.commit("setUserInfo",userInfo);
          this.$message({
            message:"登录成功!",
            type:"success"
          });
          this.$router.push("/list")
        }else{
          this.$message(res.data.msg);
        }
      })
    }
  },
  created(){

  }
}
</script>

<style scoped>
.el-form {
  width: 40%;
  margin-left: 30%;
  margin-top: 10%;
}
</style>